package com.xdcplus.web.service.bd.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.xdcplus.core.utils.BeanUtils;
import com.xdcplus.exceptions.XdcWebException;
import com.xdcplus.mom.constants.NumberConstant;
import com.xdcplus.mom.enums.ResponseEnum;
import com.xdcplus.mom.utils.ResponseUtils;
import com.xdcplus.mp.service.impl.BaseServiceImpl;
import com.xdcplus.mp.utils.PageableUtils;
import com.xdcplus.mp.utils.PropertyUtils;
import com.xdcplus.pager.vo.PageVO;
import com.xdcplus.system.api.AuthRemote;
import com.xdcplus.system.api.EmployeeRemote;
import com.xdcplus.system.api.vo.EmployeeVO;
import com.xdcplus.web.common.pojo.dto.bd.BdClassGroupUserBindDTO;
import com.xdcplus.web.common.pojo.dto.bd.BdClassGroupUserDTO;
import com.xdcplus.web.common.pojo.dto.bd.BdClassGroupUserFilterDTO;
import com.xdcplus.web.common.pojo.entity.bd.BdClassGroupUser;
import com.xdcplus.web.common.pojo.query.bd.BdClassGroupUserQuery;
import com.xdcplus.web.common.pojo.vo.bd.BdClassGroupUserVO;
import com.xdcplus.web.mapper.bd.BdClassGroupUserMapper;
import com.xdcplus.web.service.bd.BdClassGroupUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 班组与员工关联表(BdClassGroupUser)表服务实现类
 *
 * @author Fish.Fei
 * @since 2023-05-06 15:24:51
 */
@Slf4j
@Service("bdClassGroupUserService")
public class BdClassGroupUserServiceImpl extends BaseServiceImpl<BdClassGroupUserMapper, BdClassGroupUser, BdClassGroupUser, BdClassGroupUserVO> implements BdClassGroupUserService {

    @Autowired
    protected BdClassGroupUserMapper bdClassGroupUserMapper;

    @Autowired
    protected AuthRemote authRemote;

    @Autowired
    protected EmployeeRemote employeeRemote;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean saveBdClassGroupUser(BdClassGroupUserDTO bdClassGroupUserDTO) {

        BdClassGroupUser bdClassGroupUser = new BdClassGroupUser();
        BeanUtil.copyProperties(bdClassGroupUserDTO, bdClassGroupUser);

        return this.save(bdClassGroupUser);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean updateBdClassGroupUser(BdClassGroupUserDTO bdClassGroupUserDTO) {

        BdClassGroupUser bdClassGroupUser = this.getById(bdClassGroupUserDTO.getId());
        if (ObjectUtil.isNull(bdClassGroupUser)) {
            log.error("updateBdClassGroupUser() The BdClassGroupUser does not exist or has been deleted");
            throw new XdcWebException(ResponseEnum.ERROR);
        }

        BeanUtil.copyProperties(bdClassGroupUserDTO, bdClassGroupUser);

        return this.updateById(bdClassGroupUser);
    }

    @Override
    public Boolean saveOrUpdateBatch(List<BdClassGroupUser> bdClassGroupUserList) {

        bdClassGroupUserList.forEach(bdClassGroupUser -> {
            BdClassGroupUser bdClassGroupUserParam = new BdClassGroupUser();
            bdClassGroupUserParam.setId(bdClassGroupUser.getId());
            if (ObjectUtil.isNotNull(bdClassGroupUser.getId())) {
                bdClassGroupUser.setId(bdClassGroupUser.getId());
                LambdaUpdateWrapper<BdClassGroupUser> lambdaUpdate = Wrappers.lambdaUpdate();
                lambdaUpdate.eq(BdClassGroupUser::getId, bdClassGroupUser.getId());
                update(bdClassGroupUser, lambdaUpdate);
            } else {
                save(bdClassGroupUser);
            }
        });
        return true;
    }

    @Override
    public Boolean saveOrUpdateBatchByDTOList(List<BdClassGroupUserDTO> bdClassGroupUserDTOList) {

        List<BdClassGroupUser> bdClassGroupUserList = BeanUtils.copyProperties(bdClassGroupUserDTOList, BdClassGroupUser.class);
        return saveOrUpdateBatch(bdClassGroupUserList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deleteBdClassGroupUserLogical(Long id) {

        Assert.notNull(id, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());

        BdClassGroupUser bdClassGroupUser = this.getById(id);

        if (ObjectUtil.isNull(bdClassGroupUser)) {
            log.error("deleteBdClassGroupUser() The BdClassGroupUser does not exist or has been deleted");
            throw new XdcWebException(ResponseEnum.ERROR);
        }
        return this.removeById(id);
    }
    
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deleteBdClassGroupUserByIds(String ids) {
        Assert.notNull(ids, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());
		List<String> idList = Arrays.asList(ids.split(","));
		if(CollectionUtil.isEmpty(idList)){
           throw new XdcWebException(ResponseEnum.ERROR);
       }
		idList.forEach(id->{
			BdClassGroupUser bdClassGroupUser = this.getById(id);
			if (ObjectUtil.isNull(bdClassGroupUser)) {
				log.error("deleteBdClassGroupUser() The BdClassGroupUser does not exist or has been deleted");
				throw new XdcWebException(ResponseEnum.ERROR);
			}
		});
		
        return this.removeByIds(idList);
    }

    private List<BdClassGroupUser> queryBdClassGroupUserList(BdClassGroupUserFilterDTO bdClassGroupUserFilterDTO) {
        BdClassGroupUserQuery bdClassGroupUserQuery = BeanUtil.copyProperties(bdClassGroupUserFilterDTO, BdClassGroupUserQuery.class);

        return bdClassGroupUserMapper.queryBdClassGroupUser(bdClassGroupUserQuery);
    }

    @Override
    public List<BdClassGroupUserVO> queryBdClassGroupUserVOList(BdClassGroupUserFilterDTO bdClassGroupUserFilterDTO) {
        return this.objectConversion(queryBdClassGroupUserList(bdClassGroupUserFilterDTO));
    }

    @Override
    public PageVO<BdClassGroupUserVO> queryBdClassGroupUser(BdClassGroupUserFilterDTO bdClassGroupUserFilterDTO) {
        PageVO<BdClassGroupUserVO> pageVO = new PageVO<>();

        if (bdClassGroupUserFilterDTO.getCurrentPage() > NumberConstant.ZERO) {
            PageableUtils.basicPage(bdClassGroupUserFilterDTO.getCurrentPage(), bdClassGroupUserFilterDTO.getPageSize(),
                    bdClassGroupUserFilterDTO.getOrderType(), bdClassGroupUserFilterDTO.getOrderField());
        }

        List<BdClassGroupUser> bdClassGroupUserList = queryBdClassGroupUserList(bdClassGroupUserFilterDTO);

        PageInfo<BdClassGroupUser> pageInfo = new PageInfo<>(bdClassGroupUserList);
        PropertyUtils.copyProperties(pageInfo, pageVO, this.objectConversion(bdClassGroupUserList));

        return pageVO;
    }

    @Override
    public BdClassGroupUserVO queryBdClassGroupUserById(Long id) {

        Assert.notNull(id, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());

        return this.objectConversion(this.getById(id));
    }

    @Override
    public void batchBindBdClassGroupUser(BdClassGroupUserBindDTO bdClassGroupUserBindDTO) {
        bdClassGroupUserMapper.delete(new QueryWrapper<BdClassGroupUser>()
                .eq("BD_CLASS_GROUP_ID_FK", bdClassGroupUserBindDTO.getBdClassGroupIdFk()));

        if(CollectionUtil.isNotEmpty(bdClassGroupUserBindDTO.getSysEmployeeIdFks())){
            BdClassGroupUserDTO bdClassGroupUserDTO;
            for (Long sysEmployeeId : bdClassGroupUserBindDTO.getSysEmployeeIdFks()) {
                bdClassGroupUserDTO = new BdClassGroupUserDTO();
                bdClassGroupUserDTO.setBdClassGroupIdFk(bdClassGroupUserBindDTO.getBdClassGroupIdFk());
                bdClassGroupUserDTO.setSysEmployeeIdFk(sysEmployeeId);
                saveBdClassGroupUser(bdClassGroupUserDTO);
            }
        }
    }

    @Override
    public void deleteBdClassGroupUserByClassGroupId(Long classGroupId) {

        bdClassGroupUserMapper.delete(new QueryWrapper<BdClassGroupUser>().eq("BD_CLASS_GROUP_ID_FK",classGroupId));
    }

    @Override
    public BdClassGroupUserVO objectConversion(BdClassGroupUser s) {
        BdClassGroupUserVO bdClassGroupUserVO = super.objectConversion(s);
        bdClassGroupUserVO.setEmployeeName(ResponseUtils.getResponse(authRemote.queryEmployeeById(bdClassGroupUserVO.getSysEmployeeIdFk())).getName());

        return bdClassGroupUserVO;
    }

    @Override
    public List<BdClassGroupUserVO> objectConversion(List<BdClassGroupUser> sList) {
        if (!CollectionUtil.isNotEmpty(sList)) {
            return new ArrayList<>();
        } else {
            List<BdClassGroupUserVO> tList = new ArrayList();
            Iterator var3 = sList.iterator();

            List<Long> employeeIds = sList.stream().filter(a->a.getSysEmployeeIdFk()!=null).map(BdClassGroupUser::getSysEmployeeIdFk).collect(Collectors.toList());
            List<EmployeeVO> employeeVOList = ResponseUtils.getResponse(employeeRemote.queryNotRelationByIds(employeeIds));
            Map<Long, EmployeeVO> employeeVOMap = employeeVOList.stream().collect(Collectors.toMap(EmployeeVO::getId, employeeVO -> employeeVO));

            while(var3.hasNext()) {
                BdClassGroupUser s = (BdClassGroupUser)var3.next();
                BdClassGroupUserVO t = super.objectConversion(s);
                Optional.ofNullable(t).ifPresent(a->{
                    if(t.getSysEmployeeIdFk()!=null){
                        Optional.ofNullable(employeeVOMap.get(t.getSysEmployeeIdFk())).ifPresent(c -> {
                            t.setEmployeeName(c.getName());
                        });
                    }

                    tList.add(t);
                });
            }

            return tList;
        }
    }
}
